package com.mar.meclient.util;
/**
 * TODO:  Unit tests are required.
 * @author mar
 */
public class Queue {
	private final Object [] data;
	private int head;
	private int tail;
	private int size;
	
	public Queue(int maxSize) {
		if ( maxSize < 1 ){
			throw new IllegalArgumentException("max sise should be positeve!");
		}
		this.data = new Object[maxSize];
		this.size = 0;
		this.head = 0;
		this.tail = 0;
	}
	
	public int maxSize(){
		return data.length;
	}
	
	public int size(){
		return size;
	}
	
	public void push(Object element){
		checkPushPreconditions();
		data[tail] = element;
		size++;
		tail = ++tail % data.length;
	}
	
	public Object pop() {
		checkPopPrecondition();
		Object element = data[head];
		data[head] = null;// garbage collector help
		
		size--;
		head = ++head % data.length;
		
		return element;
	}

	protected void checkPopPrecondition() {
		if ( size == 0 ){
			throw new IllegalStateException("Empty queue exception!");
		}
	}

	protected void checkPushPreconditions() {
		if ( size == data.length ){
			throw new IllegalStateException("Queue oveerflow exception!");
		}
	}
	
	public static void main(String[] args) {
		Queue queue = new Queue(2);
		queue.push("1");
		queue.push("2");
		System.out.println(queue.pop());
		System.out.println(queue.pop());

		queue.push("3");
		queue.push("4");
		
		System.out.println(queue.pop());
		System.out.println(queue.pop());
	}
}
